<?php

namespace app\api\model;

use think\Exception;
use think\Model;
use think\Db;
use think\Validate;

class ClaimPersons extends Model
{
    private static $instance = null;

    public function __construct($data = [])
    {
        parent::__construct($data);
    }

    public function checkout($data)
    {
        $validate = new Validate([
                    'name'  => 'require|max:20',
                    'company_id' => 'require',
                    'address' => 'require|max:50',
                    'remarks'=>'require',
                    'tel' => 'require|max:11|/^1[3-8]{1}[0-9]{9}$/',
                    'wechat' => 'require'
                ]);
        if (!$validate->check($data)) {
            return ["code"=>"100","msg"=>$validate->getError()];
        }
    }
    /**
     * 获取理赔人员列表
     */
    public function getList($param)
    {
        $where = [];

        $page = 1;
        //分页
        if(isset($param['page'])) {
            $page = $param['page'];
        }
        //偏移位置
        $offset = ($page-1) * 10;

        //搜索
        if(isset($param['company_id'])) {
            $where['company_id'] = $param['company_id'];
        }
        if(isset($param['name'])) {
            $where['name'] = array("like","%".$param['name']."%");
        }
        if(isset($param['tel'])) {
            $where['tel'] = array("like","%".$param['tel']."%");
        }

        $data = Db::name("claim_persons")->where($where)->limit($offset,10)->select();

        foreach($data as $key => $val) {
            $data[$key]['company_name'] = config("companys.list")[$val['company_id']];
            $data[$key]['update_time'] = date("Y-m-d Y:i:s",$val['update_time']);
        }
        $res['total'] = Db::name("claim_persons")->where($where)->count();
        $res["list"] = $data;

        return $res;
    }

    /**
     * 获取单条理赔详情
     */
    public function detail($param)
    {
        $data = Db::name("claim_persons")->where("id",$param['id'])->find();
        $data['company_name'] = config("companys.list")[$data['company_id']];
        $data['update_time'] = date("Y-m-d Y:i:s",$data['update_time']);
        return $data;
    }

    /**
     * 添加或修改理赔人员
     */
    public function addPerson($param)
    {
        $check = $this->checkout($param);
        if($check['code']=="100") {
            return array('code' => 100,'msg' => $check['msg']);
        }
        if(isset($param['id'])) {
            $id = $param['id']; unset($param['id']);
            $param['update_time'] = time();
            $res = Db::name("claim_persons")->where("id",$id)->update($param);
            if($res) {
                return array('code' => 200,'msg' => "Success");
            }
        } else {
            $param['add_time'] = time();
            $param['update_time'] = time();
            $res = Db::name("claim_persons")->insert($param);
            if($res) {
                return array('code' => 200,'msg' => "Success");
            }
        }
    }
}

?>